// 添加彩色输出的辅助函数
const colors = {
  green: (text) => `\x1b[32m${text}\x1b[0m`,
  blue: (text) => `\x1b[34m${text}\x1b[0m`,
  yellow: (text) => `\x1b[33m${text}\x1b[0m`,
  cyan: (text) => `\x1b[36m${text}\x1b[0m`,
};

// 获取支持的模型列表
export async function getModels(ctx) {
  try {
    // 导入模型配置
    const { getSupportedModels } = await import("../config/models.js");

    ctx.body = {
      success: true,
      data: getSupportedModels(),
    };
  } catch (error) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: "获取模型列表失败",
      error: process.env.DEBUG === "true" ? error.message : undefined,
    };
  }
}

// 处理AI对话
export async function chat(ctx) {
  console.log(colors.blue(JSON.stringify(ctx.request.body)));
  try {
    const { model, messages } = ctx.request.body;
    const { sendChatRequest } = await import("../utils/sendApi.js");

    // 发送聊天请求
    console.log(colors.yellow(JSON.stringify(model)));
    console.log(colors.yellow(JSON.stringify(messages[0])));

    // 发送请求到千帆API
    const response = await sendChatRequest(model, messages);
    console.log(colors.green(JSON.stringify(response)));

    ctx.body = {
      success: true,
      data: response,
    };
  } catch (error) {
    console.log(colors.cyan(error));
    ctx.status = error.status || 500;
    ctx.body = {
      success: false,
      message: error.message || "请求失败",
      error: process.env.DEBUG === "true" ? error.stack : undefined,
    };
  }
}

// 健康检查
export async function healthCheck(ctx) {
  ctx.body = {
    success: true,
    message: "Server is running and API credentials are valid",
    timestamp: new Date().toISOString(),
  };
}
